package pneuservis.frontend.web;

import java.io.IOException;
import javax.ejb.EJB;


import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import pneuservis.backend.services.CustomerServiceLocal;
import pneuservis.backend.to.CustomerTO;

public class LoginUser extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

    static final long serialVersionUID = 1L;
    @EJB(lookup = "java:global/cz.muni.fi.pa165.pneuservis_Pneuservis-ear_ear_1.0-SNAPSHOT/Pneuservis-ejb-1.0-SNAPSHOT/CustomerService")
    private CustomerServiceLocal customerService;

    public LoginUser() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = (new Sha256Hash(request.getParameter("password"))).toHex();
        System.out.println(password);
        try {

            Subject subject = SecurityUtils.getSubject();
            subject.login(new UsernamePasswordToken(username, password));

            if (subject.hasRole("admin")) {
                response.sendRedirect("/pa165/orders/all");
            } else if (subject.hasRole("Customer")) {
                response.sendRedirect("/pa165/auth/signin");
            } else {
                throw new IllegalStateException("user with unknown role has logged in");
            }
            return;
        } catch (UnknownAccountException ex) {
            response.sendRedirect("/pa165/failedLogin.jsp");
        } catch (IncorrectCredentialsException ex) {
            response.sendRedirect("/pa165/failedLogin.jsp");
        } catch (Exception ex) {
            response.sendRedirect("/pa165/failedLogin.jsp");
        }

    }
}